package charlie.shop.admin;

import charlie.shop.misc.Common;
import com.charlie.beans.Roles;
import com.charlie.beans.Users;
import com.charlie.beans.UsersRole;
import com.charlie.db.DAOLocal;
import com.charlie.sessions.RolesFacadeLocal;
import com.charlie.sessions.UsersFacadeLocal;
import com.charlie.sessions.UsersRoleFacadeLocal;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Edit user servlet
 *
 * @author Оленка
 */
@WebServlet(name = "EditUser", urlPatterns = {"/admin/editUser"})
public class EditUser extends HttpServlet {

    @EJB
    private UsersFacadeLocal usersFacade;
    @EJB
    private RolesFacadeLocal rolesFacade;
    @EJB
    private UsersRoleFacadeLocal usersRoleFacade;
    @EJB
    private DAOLocal dao;

    /**
     * Remove role from user
     *
     * @param userId user id
     * @param roleName name of role
     * @throws ServletException if a servlet-specific error occurs
     * @throws SQLException if a sql-specific error occurs
     */
    void removeUsersRole(int userId, String roleName) throws ServletException, SQLException {
        dao.deleteUsersRole(userId, rolesFacade.findByRolesName(roleName).getRolesId());
    }

    /**
     * Processes users-roles data
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Common.getParametrInt(request, "userId", 0);
        Users user = usersFacade.findByUsersId(id);

        request.setAttribute("current_user", user);
        request.setAttribute("rolesList", rolesFacade.findAll());

        List<String> rolesName = dao.getUserPersonalRolesByEmail(user.getEmail());
        request.setAttribute("userRolesName", rolesName);

        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/admin/editUser.jsp").forward(request, response);
    }

    /**
     * Edit current user
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int id = Common.getParametrInt(request, "userId", 0);
        Users user = usersFacade.findByUsersId(id);

        String email = request.getParameter("email");
        String first_name = request.getParameter("first_name");
        String second_name = request.getParameter("second_name");
        String location = request.getParameter("location");
        String password = request.getParameter("pass");
        String password2 = request.getParameter("pass2");

        boolean errors = false;

        if (!usersFacade.emailIsValid(email)) {
            errors = true;
        } else if (!user.getEmail().equals(email) && usersFacade.findByEmail(email) != null) {
            errors = true;
            request.setAttribute("email_exist", email);
        }

        if (password == null || password.length() == 0 || !password.equals(password2)) {
            errors = true;
        }

        if (!usersFacade.nameIsValid(first_name)) {
            errors = true;
        }

        if (!usersFacade.nameIsValid(second_name)) {
            errors = true;
        }

        if (location == null || location.length() == 0) {
            errors = true;
        }

        if (errors) {
            request.setAttribute("validate", true);
            processRequest(request, response);
            return;
        }

        user.setEmail(email);
        user.setPassword(password);
        user.setFirstName(first_name);
        user.setSecondName(second_name);
        user.setLocation(location);
        usersFacade.edit(user);

        //for checkboxes
        String select[] = request.getParameterValues("id");
        List<String> rolesName = dao.getUserPersonalRolesByEmail(user.getEmail());
        if (select != null) {
            //check if some user role was uncheked
            boolean b;
            for (String r : rolesName) {
                b = false;
                for (String chr : select) {
                    if (r.equals(chr)||(r.equals("Admin"))) {
                        b = true;
                        break;
                    }
                }
                //if role was uncheked - delete it
                if (!b) {
                    try {
                        removeUsersRole(user.getUsersId(), r);
                    } catch (SQLException ex) {
                        Logger.getLogger(EditUser.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            if (select.length != 0) {
                for (String roleName : select) {
                    //if user has not had cheked role yet
                    if (!rolesName.contains(roleName)) {
                        UsersRole ur = new UsersRole();
                        Roles role = rolesFacade.findByRolesName(roleName);
                        ur.setRolesId(role);
                        ur.setUsersId(user);
                        usersRoleFacade.create(ur);
                    }
                }
            }
        }

        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/admin/completeEdition.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    } 
}
